package logic

import (
	"github.com/gin-gonic/gin"
	"iot-base/auth/model"
	"iot-base/auth/svc"
	"iot-base/auth/utils"
	"strconv"
	"strings"
)

type RoleLogic struct {
}

func NewRoleLogic() *RoleLogic {
	return &RoleLogic{}
}

// FindRole 查询角色.
func (r *RoleLogic) FindRole(userId, groupId int64, page int, size int) (gin.H, error) {
	resp := gin.H{
		"total": 0,
		"list":  make([]interface{}, 0, 1),
	}
	// 查询用户的当前的角色ID
	roleList, err := svc.Dao.TAuthRole.GetRole(userId, groupId)
	if err != nil {
		return resp, err
	}
	if len(roleList) <= 0 {
		return resp, nil
	}
	// 查询所有的角色
	total, err := svc.Dao.TAuthRole.FindRoleCount(roleList[0].ID)
	if err != nil {
		return resp, err
	}
	list, err := svc.Dao.TAuthRole.FindRole(roleList[0].ID, page, size)
	if err != nil {
		return resp, err
	}
	resp["total"] = total
	resp["list"] = list
	return resp, nil
}

// AddRole 添加角色
func (r *RoleLogic) AddRole(userId int64, groupId int64, name string, rules []int64) error {
	// 查询用户的当前的角色ID
	rouleList, err := svc.Dao.TAuthRole.GetRole(userId, groupId)
	if err != nil {
		return err
	}
	roleInfo := &model.AuthRole{}
	roleInfo.ID = utils.GetUid()
	roleInfo.RoleName = name
	rulesStr := ""
	for _, v := range rules {
		rulesStr += strconv.FormatInt(v, 10) + ","
	}
	roleInfo.Rules = strings.Trim(rulesStr, ",")
	if len(rouleList) > 0 {
		roleInfo.Pid = rouleList[0].ID
		path := rouleList[0].Path + "/" + strconv.FormatInt(rouleList[0].ID, 10)
		roleInfo.Path = strings.Trim(path, "/")
	}
	err = svc.Dao.TAuthRole.AddAuthRole(roleInfo)
	return err
}

// DelRole 删除角色.
func (r *RoleLogic) DelRole(id int64) (int64, error) {
	return svc.Dao.TAuthRole.DelRole(id)
}

// EditRole 修改角色.
func (r *RoleLogic) EditRole(id int64, name string, roles []int64) (int64, error) {
	roleStr := ""
	for _, v := range roles {
		roleStr += strconv.FormatInt(v, 10) + ","
	}
	return svc.Dao.TAuthRole.UpdateRole(id, name, strings.Trim(roleStr, ","))
}
